package com.clx.rmp.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

@Slf4j
public class FileUtil {

    public static List<String> readByLine(String filePath) {
        return readByLine(new File(filePath));
    }

    public static List<String> readByLine(File file) {
        List<String> list = new LinkedList<>();
        if (file == null || !file.exists()) {
            return list;
        }

        String line = null;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                list.add(line);
            }

        } catch (Exception e) {
            log.error("文件读取异常", e);
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;
    }

    public static String read(File filePath) {
        byte[] bytes = readByte(filePath);
        return new String(bytes);
    }

    public static byte[] readByte(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }
        return readByte(new File(filePath));
    }

    /**
     * 读取文件
     *
     * @param file
     * @return
     */
    public static byte[] readByte(File file) {
        if (file == null && !file.exists()) {
            return null;
        }

        InputStream is = null;
        ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
        try {
            int len;
            byte[] temp = new byte[1024];
            is = new FileInputStream(file);
            while ((len = is.read(temp)) != -1) {
                outBuffer.write(temp, 0, len);
            }
        } catch (Exception e) {
            log.error("文件读取异常filePath={}", file.getAbsoluteFile(), e);
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("文件流关闭异常filePath={}", file.getAbsoluteFile(), e);
                    return null;
                }
            }
        }

        return outBuffer.toByteArray();
    }

    public static boolean write(String filePath, String fileContent, boolean isOver) {
        File file = new File(filePath);
        if (file.exists() && isOver) {
            file.delete();
        }
        return write(file, fileContent);
    }

    public static boolean write(String filePath, String fileContent) {
        File file = new File(filePath);
        return write(file, fileContent);
    }

    public static boolean write(File file, String fileContent) {
        byte[] bytes = null;
        if (StringUtils.isNotBlank(fileContent)) {
            bytes = fileContent.getBytes();
        }
        return writeByte(file, bytes);
    }

    public static boolean writeByte(String filePath, byte[] bytes) {
        if (StringUtils.isBlank(filePath)) {
            return false;
        }

        File file = new File(filePath);
        return writeByte(file, bytes);
    }

    /**
     * 将数据写入文件
     *
     * @param file  文件路径
     * @param bytes 文件内容(如果内容空,则只创建文件)
     * @return
     */
    public static boolean writeByte(File file, byte[] bytes) {
        if (file == null) {
            return false;
        }

        //文件中无内容
        if (bytes == null) {
            bytes = new byte[0];
        }

        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(bytes);
            return true;
        } catch (Exception e) {
            log.error("文件写异常filePath={}", file.getAbsoluteFile(), e);
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("输出流关闭异常filePath={}", file.getAbsoluteFile(), e);
                }
            }
        }
    }

    public static Properties readProperties(File file) {
        Properties properties = new Properties();
        // 使用InPutStream流读取properties文件
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            properties.load(bufferedReader);
        } catch (Exception e) {
            log.error("Properties文件读取失败", e);
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return properties;
    }

    public static Properties readProperties(String filePath) {
        File f = new File(filePath);
        if (f.exists()) {
            return readProperties(f);
        } else {
            return null;
        }
    }

    public static List<File> listCurrentDirFile(File file) {
        List<File> list = new LinkedList<>();
        if (file != null) {
            for (File f : file.listFiles()) {
                if (!f.isDirectory()) {
                    list.add(f);
                }
            }
        }
        return list;
    }

    public static List<File> listCurrentDirFile(String dirPath) {
        if (StringUtils.isBlank(dirPath)) {
            return new LinkedList<>();
        }
        return listCurrentDirFile(new File(dirPath));
    }

    public static List<File> listFile(File file) {
        return listFile(file, null, null);
    }

    public static List<File> listFile(String dirPath) {
        if (StringUtils.isBlank(dirPath)) {
            return new LinkedList<>();
        }
        return listFile(new File(dirPath), null, null);
    }

    public static List<File> listFile(String dirPath, String incloud, String endWith) {
        if (StringUtils.isBlank(dirPath)) {
            return new LinkedList<>();
        }
        return listFile(new File(dirPath), incloud, endWith);
    }

    /***
     * 获取指定目录下的所有的文件（不包括文件夹），采用了递归
     *
     * @param file
     * @return
     */
    public static List<File> listFile(File file, String include, String endWith) {
        List<File> fileList = new LinkedList<>();
        if (file == null) {
            return fileList;
        }

        if (!file.exists()) {
            return fileList;
        }

        if (file.isFile()) {
            fileList.add(file);
        }

        int paramNotNullNum = 0;
        if (include != null) {
            paramNotNullNum++;
        }
        if (endWith != null) {
            paramNotNullNum++;
        }

        File[] childFileList = file.listFiles();
        for (File childFile : childFileList) {
            if (childFile.isFile()) {
                int condition = 0;
                String path = childFile.getAbsolutePath();
                if (include != null && path.contains(include)) {
                    condition++;
                }

                if (endWith != null && path.endsWith(endWith)) {
                    condition++;
                }

                if (condition == paramNotNullNum) {
                    fileList.add(childFile);
                }
            } else {
                fileList.addAll(listFile(childFile, include, endWith));
            }
        }

        return fileList;
    }

    public static int copyFile(File srcFile, File desFile, boolean isOver) {
        if (!srcFile.exists()) {
            return -2;
        }

        Boolean writeFlag = true;
        if (desFile.exists()) {
            if (isOver) {
                desFile.delete();
            } else {
                writeFlag = false;
            }
        }

        if (writeFlag) {
            try {
                byte[] bytes = FileUtil.readByte(srcFile);
                FileUtil.writeByte(desFile, bytes);
            } catch (Exception e) {
                log.error("文件读取异常", e);
                return -1;
            }
        }
        return 1;
    }

    public static boolean mkdir(File webFilePath) {
        if (!webFilePath.exists()) {
            File parentFile = webFilePath.getParentFile();
            parentFile.mkdirs();
            return true;
        } else {
            return true;
        }
    }
}
